var clientPC = navigator.userAgent.toLowerCase();
var clientVer = parseInt(navigator.appVersion);
var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var set_on = false;

if(!Object.keys){ 
	Object.keys = function(obj){ 
		var ret = new Array(); 
		for(var key in obj){ 
			ret.push(key); 
		} 
		return ret; 
	}; 
}


function message(mes)
{
	alert(mes);
}

function getparent(){
	if(globalPernt){
		return true;
	}
	return false;
}

function countHash(hash){
	var counter = 0;
    for( var k in hash )
        counter++
    return counter
}
function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

// Версия картинок
var ImgVer = "0.0.0.1";

// Обменник - смена иконки предмета на которую хотим обменять ресурс
function changerChangeImg(id)
{
	$("div.resChange img#changeImg").attr("src", iServer+'/i/items/item_'+id+'.png');
}


function print_r( array, return_val ) {    // Prints human-readable information about a variable

    var output = "", pad_char = " ", pad_val = 4;
 
    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if(cur_depth > 0)
            cur_depth++;
 
        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";
 
        if(obj instanceof Array || obj instanceof Object) {
            str += "Array\n" + base_pad + "(\n";
            for(var key in obj) {
                if(obj[key] instanceof Array || obj[key] instanceof Object) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";
        } else {
            str = obj.toString();
        };
 
        return str;
    };
 
    var repeat_char = function (len, chr) {
        var str = "";
        for(var i=0; i < len; i++) { str += chr; };
        return str;
    };
 
    output = formatArray(array, 0, pad_val, pad_char);
 
    if(return_val !== true) {
        return "<pre>" + output + "</pre>";
        //document.write("<pre>" + output + "</pre>");
        //return true;
    } else {
        return "<pre>" + output + "</pre>";
    }
}

function print_json_pc (obj)
{
	return Object.keys(obj).length;
}

function print_json( array, return_val ) {    // Prints human-readable information about a variable

    var output = "", pad_char = " ", pad_val = 4;
 
    var formatArray = function (obj, cur_depth, pad_val, pad_char, parent_count1, parent_count2) {
        if(cur_depth > 0)
            cur_depth++;
 
        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";
        var lstr = "";
 
        if(obj instanceof Array || obj instanceof Object) {
            str += "\n" + base_pad + "{\n";            
            var ocount = print_json_pc(obj);            
            var oindex = 0;
            for(var key in obj) {
            	oindex ++;
                if(obj[key] instanceof Array || obj[key] instanceof Object) {
                	if (typeof obj[key] == "number")
                	{
                    	str += thick_pad + ""+key+" : "+formatArray(obj[key], cur_depth+1, pad_val, pad_char, print_json_pc(obj), print_json_pc(obj[key]));                    	
					}
                    else                    
                    {
                    	str += thick_pad + "\""+key+"\" : "+formatArray(obj[key], cur_depth+1, pad_val, pad_char, print_json_pc(obj), print_json_pc(obj[key]));
					}					
					var nzap = ",";         
                	if (oindex == ocount)       	
                		nzap = "";			
                	str += repeat_char(pad_val*1, pad_char)+thick_pad + "}"+nzap+" \n";							
                } else {                	                	
                	var nzap = ",";         
                	if (oindex == ocount)       	
                		nzap = "";
                	if (typeof obj[key] == "number")
                    	str += thick_pad + "\""+key+"\" : " + obj[key] + ""+nzap+" \n";
                    if (typeof obj[key] == "boolean")
                    	str += thick_pad + "\""+key+"\" : " + obj[key] + ""+nzap+" \n";
                    if (typeof obj[key] == "undefined")
                    	str += thick_pad + "\""+key+"\" : " + "null" + ""+nzap+" \n";                    
                    if (typeof obj[key] == "string")
                    	str += thick_pad + "\""+key+"\" : \"" + obj[key] + "\""+nzap+" \n";                    	                    	
                }
            }
            var nzapp = ",";            
            
            
            
        } else {
            str = obj.toString();
        };
 
        return str;
    };
 
    var repeat_char = function (len, chr) {
        var str = "";
        for(var i=0; i < len; i++) { str += chr; };
        return str;
    };
 
    output = formatArray(array, 0, pad_val, pad_char, print_json_pc(array));
    output += "}";
 
    if(return_val !== true) {
        return "<pre>" + output + "</pre>";
        //document.write("<pre>" + output + "</pre>");
        //return true;
    } else {
        return "<pre>" + output + "</pre>";
    }
}

	// Клонирование обьекта
	function clone(o) {
		if(!o || "object" !== typeof o)  {
			return o;
		}
		var c = "function" === typeof o.pop ? [] : {};
		var p, v;
		for(p in o) {
			if(o.hasOwnProperty(p)) {
				v = o[p];
				if(v && "object" === typeof v) {
					c[p] = clone(v);
				}
			else c[p] = v;
			}
		}
		return c;
	}

// Форматирует строку
function formatstr(fmt){
	var retValue = fmt;
	
 	for (var i = 1; i < formatstr.arguments.length; i++)
 	{
 		var sp = '{' + (i - 1) + '}'; 		 			
 		retValue = replacestr(retValue, sp, '' + formatstr.arguments[i]); 		
 	}

 	return retValue;
}
function replacestr(source, what, replaceWith)
{
	var retValue = [];
 	var i;
 	while (true)
 	{ 		
 		i = source.indexOf(what);
 		if (i >= 0)
 		{
 			retValue.push(source.substr(0, i));
 			retValue.push(replaceWith);
 			source = source.substr(i + what.length);
 		}
 		else
 		{
 			break;
 		}
 	}
 	retValue.push(source);
 	return retValue.join('');
}

function formatIntToTime(str){
	var theDate = new Date(str * 1000);
	var d = formatDateNull(theDate.getDate());
	var m = formatDateNull( theDate.getMonth() + 1 );
	var y = formatDateNull(theDate.getFullYear());
	var h = formatDateNull(theDate.getHours());
	var i = formatDateNull(theDate.getMinutes());

	var ret = d +"."+ m +"."+ y +" "+ h +":"+ i;
	return ret;
}

function formatDateNull(str){
	if(str < 10){
		return "0"+str;
	}else{
		return str;
	}

}


function formatSecToTime(sec){
	var a = {
			86400 : 'дней', // количество секунд в сутках
			3600  : 'час.', // количество секунд в часе
			60    : 'мин.', // количество секунд в минуте
			1     : 'сек.' // количество секунд в секунде
			}
	 var out = '';
	 for(var key in a) {
		  var tmp = Math.floor(sec/key);
		  out +=(tmp != 0) ? tmp+" "+a[key] : '';
		  sec -= tmp * key;
	 }
	 return out;
}

function loadAjax(hash, callBack){
	if(!hash){
		var hash = {};
	}
	hash.ajax = 1;
	params = $.param(hash);
	$.post('/?'+params, {}, function(json){
		$("#debug").html((json.error));
		/*$("#content_dialog").html(json.error);
		openDialog();*/
		$("#debug").css('padding', '5px');
		$("#debug").append((json));
		if(json.result && callBack == null){
			for(key in json.result){
				var tmp = json.result[key];			
				if(tmp["redirect"]){
					top.location=tmp["redirect"];
				}		
				if(tmp["act"]==0){
					$("#"+tmp["div"]).html(tmp["cont"]);
				}else if(tmp["act"]==1){
					$("#"+tmp["div"]).append(tmp["cont"]);
				}else if(tmp["act"]==2){
					$("#"+tmp["div"]).prepend(tmp["cont"]);
				}else if(tmp["act"]==3){
					$("#"+tmp["div"]).html("");
				}			
				if(tmp["style"]){
					for(var k in tmp["style"]){
						$("#"+tmp["div"]).css([k],tmp["style"][k]);
					}
				}
				if(tmp["js"]){
					eval(tmp["js"]);
				}
						
			}
		}else if(json.result && callBack){
			callBack(json.result);
		
		}
		
		if(json.debug)
		{
			var html = '<br><br>';
			var sql = [];
			var param = [];
			html = print_r(json.debug, false);
		}
	}, "json");	
}

function getAjax(hash, callBack){
	if(callBack){
		callBack = null;
	}
	if(window.frames['gameFrame']){
		window.frames['gameFrame'].loadAjax(hash);
	}else{
		loadAjax(hash, callBack);
	}
}

